using System;
using Jink.Core;
using Jink.Core.Json;
using Jink.Core.Json.Values;
using Jink.Protocol;
using XenoGears.Assertions;

namespace Jink.Playground.MockProtocol
{
    internal static class JinkMock
    {
        public static JsonValue Send(String url, String verb)
        {
            return Send(url, verb, null);
        }

        public static JsonValue Send(String url, String verb, Object form)
        {
            var proto = new JinkProtocol();
            proto.Add(_ => true, new CoreProtocolModule());

            var req = new MockRequestMedia(url, verb, form);
            var resp = new MockResponseMedia();
            proto.Process(req, resp);

            (verb != "PUT").AssertImplies(resp.StatusCode == 200);
            (verb == "PUT").AssertImplies(resp.StatusCode == 201);

            var json = resp.Content.ToString().ParseJson();
            (json["errorCode"] == 0).AssertTrue();
            (json["statusCode"] == (verb != "PUT" ? 200 : 201)).AssertTrue();
            json.ContainsKey("exception").AssertImplies(json["exception"] == null);
            json.ContainsKey("trace").AssertImplies(((JsonExpression)json["trace"]).Value is String);

            return json["result"];
        }
    }
}